package com.example.connect;

import android.content.Context;
import android.os.AsyncTask;

import com.example.appcontact.A002Login;
import com.example.appcontact.R;
import com.example.model.OutResult;
import com.example.util.Util;


public class AsyncTask_Api extends AsyncTask<Long, Void, Object> {

	public static final int API_TYPE_NONE = 0;
	public static final int API_TYPE_REGISTER = 1;
	private int searchType = 0;

	private Context m_context = null;

	private Object m_apiData = null;

	AsyncTask_ApiListener m_interface = null;

	private ScreenStopper stopperDlg = null;


	
	void init(Context context , AsyncTask_ApiListener _interface,
			int type, Object apidata, int alertStyle)
	{
		
			m_context = context;
			m_interface =_interface;
			searchType = type;
			m_apiData = apidata;
          if(alertStyle != ScreenStopper.STYLE_NONE){
        	  switch (alertStyle)
  			{
  				case ScreenStopper.STYLE_PROGRESS_PROCESS:
  					stopperDlg = ScreenStopper.createScreenStopperProcess(m_context);
  					break;
  				case ScreenStopper.STYLE_PROGRESS_VOTE:
  					stopperDlg = ScreenStopper.createScreenStopperVote(m_context);
  					break;
  				case ScreenStopper.STYLE_PROGRESS_DRAFT:
  					stopperDlg = ScreenStopper.createScreenStopperDraft(m_context);
  					break;
  				case ScreenStopper.STYLE_PROGRESS_LOADING:
  					stopperDlg = ScreenStopper.createScreenStopperLoading(m_context);
  					break;
  				default:
  					stopperDlg = ScreenStopper.createScreenStopperTrans(m_context);
  					break;
  			}
  			stopperDlg.show();
          }
		
		
	}


	
	public AsyncTask_Api(Context context , AsyncTask_ApiListener _interface, int type, Object apidata)
	{
		init(context , _interface,
				type, apidata, ScreenStopper.STYLE_STOPPER);
	}

	
	public AsyncTask_Api(Context context , AsyncTask_ApiListener _interface,
			int type, Object apidata, int alertStyle)
	{
		init(context , _interface,
				type, apidata, alertStyle);
	}


	@Override
	protected Object doInBackground(Long... params) {
		if (m_interface == null)
		{
			return null;
		}
		return m_interface.callApi(searchType, m_apiData);
	}

	@Override
	protected void onPostExecute(Object apiresult)
	{
		if(stopperDlg != null) stopperDlg.dismiss();
		stopperDlg = null;
		if (m_interface != null){
			try{
				OutResult out  = (OutResult) apiresult;
				if(out != null){
					
					if(out.getCode() ==  OutResult.CODE_OK && out.getStatus()){
						m_interface.finishApi(searchType, apiresult);
					}else{
						if(out.getCode() == OutResult.CODE_TOKEN){
							m_interface.tokenExpride();
						}else{
							Util.showDialog(m_context,R.string.error, out.getMessage(), R.drawable.exclamation);
						}
						
					}
				}
			}catch(Exception e){
				m_interface.finishApi(searchType, apiresult);
			}
		}
		super.onPostExecute(apiresult);
	}

}
